<template>
  <!-- 右侧配置面板 -->
  <div class="config-panel" :class="{ 'is-visible': modelValue }">
    <!-- 面板头部 -->
    <div class="panel-header">
      <span class="panel-title">文章设置</span>
      <el-button link class="close-btn" @click="$emit('update:modelValue', false)">
        <el-icon><Close /></el-icon>
      </el-button>
    </div>

    <!-- 面板主体 -->
    <div class="panel-body">
      <el-form :model="articleForm" label-position="top" size="large">
        <!-- 封面图上传 -->
        <el-form-item label="封面图" class="block-item">
          <div class="cover-uploader">
            <el-upload
              class="uploader"
              action="/commonApi/upload"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :on-success="handleCoverSuccess"
              accept="image/*"
              :data="{ filePath: 'cover' }"
            >
              <el-image
                v-if="articleForm.picUrl"
                :src="articleForm.picUrl"
                class="cover-image"
                fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div v-else class="upload-placeholder">
                <el-icon><Picture /></el-icon>
                <span>设置封面图</span>
              </div>
            </el-upload>
            <el-button
              v-if="articleForm.picUrl"
              class="delete-cover"
              type="danger"
              link
              @click="handleDeleteCover"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </el-form-item>

        <!-- 封面风格选择 -->
        <el-form-item v-if="articleForm.picUrl" label="封面风格" class="block-item">
          <el-radio-group v-model="articleForm.coverStyle" class="cover-style-group">
            <el-radio-button value="1">小图</el-radio-button>
            <el-radio-button value="2">大图</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 分类选择 -->
        <el-form-item>
          <template #label>
            <div class="form-label-wrap">
              <span class="required">分类</span>
            </div>
          </template>
          <el-select
            v-model="articleForm.categoryId"
            placeholder="请选择分类"
            :loading="categoryLoading"
            class="w-full"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 标签选择 -->
        <el-form-item label="标签">
          <el-select
            v-model="articleForm.tags"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="选择或输入标签"
            :remote-method="handleTagSearch"
            :loading="tagLoading"
            :allow-create="true"
            @create="handleCreateTag"
            class="w-full"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            >
              <span class="tag-option">
                <el-tag
                  size="small"
                  :style="{ backgroundColor: item.color + '1a', color: item.color }"
                >
                  {{ item.name }}
                </el-tag>
                <span class="tag-count" v-if="item.count">{{ item.count }}篇文章</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 文章类型 -->
        <el-form-item>
          <template #label>
            <div class="form-label-wrap">
              <span class="required">文章类型</span>
            </div>
          </template>
          <el-radio-group v-model="articleForm.type" class="type-group">
            <el-radio-button value="1">公开</el-radio-button>
            <el-radio-button value="2">私密</el-radio-button>
            <el-radio-button value="3">加密</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 访问密码输入框 -->
        <el-form-item label="访问密码" v-if="articleForm.type === '3'">
          <el-input
            v-model="articleForm.password"
            type="password"
            placeholder="请输入访问密码"
            show-password
            class="mt-2"
            required
          />
        </el-form-item>

        <!-- 文章状态 -->
        <el-form-item>
          <template #label>
            <div class="form-label-wrap">
              <span class="required">文章状态</span>
            </div>
          </template>
          <el-radio-group v-model="articleForm.status">
            <el-radio value="0">草稿</el-radio>
            <el-radio value="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 排序值 -->
        <el-form-item>
          <template #label>
            <div class="form-label-wrap">
              <span>排序值</span>
              <el-tooltip content="数值越小，排序越靠前" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="order-input">
            <el-input-number
              v-model="articleForm.orderNum"
              :min="0"
              :max="999"
              controls-position="right"
              placeholder="请输入排序值"
              class="w-full"
            />
          </div>
        </el-form-item>

        <!-- 文章摘要 -->
        <el-form-item class="block-item">
          <template #label>
            <div class="form-label-wrap">
              <span>文章摘要</span>
              <el-tooltip content="未填写将自动根据文章内容生成" placement="top">
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="summary-wrapper">
            <el-input
              v-model="articleForm.description"
              type="textarea"
              :rows="6"
              placeholder="简短的文章介绍..."
              resize="none"
              maxlength="500"
              show-word-limit
              class="w-full"
            />
            <div class="auto-generate" :class="{ 'is-generating': isGenerating }">
              <el-tooltip
                :content="isGenerating ? 'AI正在生成摘要...' : 'AI生成摘要'"
                placement="top"
              >
                <el-button
                  class="generate-btn"
                  :loading="isGenerating"
                  :disabled="isGenerating"
                  @click="handleAutoGenerate"
                >
                  <el-icon v-if="!isGenerating"><Cpu /></el-icon>
                  <span v-if="isGenerating" class="generating-text">生成中...</span>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { Close, Picture, InfoFilled, Cpu, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { tagApi } from '@/api/tag'
import { articleApi } from '@/api/article'
import { categoryApi } from '@/api/category'
import { getThemeVariables } from '@/utils/themeUtils'

// Props 定义
const props = defineProps({
  // v-model绑定值，控制面板显示/隐藏
  modelValue: {
    type: Boolean,
    required: true,
  },
  // 文章表单数据
  articleForm: {
    type: Object,
    required: true,
    default: () => ({
      type: '1', // 默认公开
      status: '0', // 默认草稿
      category: '1', // 默认分类
      password: '',
      coverStyle: '0', // 默认无图模式
      // ... 其他属性
    }),
  },
})

// Emits 定义
const emit = defineEmits([
  'update:modelValue', // 更新面板显示状态
  'update:articleForm', // 更新文章表单数据
])

// 标签相关
const tagLoading = ref(false)
const tagOptions = ref([])

// 自动生成摘要相关
const isGenerating = ref(false)

// 分类相关
const categoryLoading = ref(false)
const categoryOptions = ref([])

// 获取主题色
const primaryColor = getThemeVariables()['--primary-color']

// 获取分类列表
const fetchCategories = async () => {
  try {
    categoryLoading.value = true
    const res = await categoryApi.getList({
      pageSize: 999, // 获取所有分类
      status: '1', // 只获取启用的分类
    })
    if (res?.records) {
      // 确保默认分类始终存在
      const hasDefault = res.records.some((item) => item.id === '1')
      if (!hasDefault) {
        res.records.unshift({
          id: '1',
          name: '默认分类',
        })
      }
      categoryOptions.value = res.records
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    // 至少保留默认分类选项
    categoryOptions.value = [
      {
        id: '1',
        name: '默认分类',
      },
    ]
  } finally {
    categoryLoading.value = false
  }
}

// 组件挂载时获取分类列表并确保默认值
onMounted(() => {
  fetchCategories()
  // 确保默认值设置
  if (!props.articleForm.type) {
    props.articleForm.type = '1'
  }
  if (!props.articleForm.status) {
    props.articleForm.status = '0'
  }
  if (!props.articleForm.category) {
    props.articleForm.category = '1'
  }
})

// 标签搜索处理
const handleTagSearch = async (query) => {
  if (!query) {
    // 不清空标签选项，保留已加载的标签
    return
  }

  try {
    tagLoading.value = true
    const res = await tagApi.searchTags(query)
    // 获取新的标签选项
    const newOptions = (res.records || []).map((tag) => ({
      name: tag.name,
      color: tag.color || primaryColor,
      count: tag.articleCount || 0,
    }))

    // 合并新的标签选项，避免清空已有选项
    const existingNames = tagOptions.value.map((item) => item.name)
    const filteredNewOptions = newOptions.filter((item) => !existingNames.includes(item.name))
    tagOptions.value = [...tagOptions.value, ...filteredNewOptions]
  } catch (error) {
    console.error('搜索标签失败:', error)
  } finally {
    tagLoading.value = false
  }
}

// 创建新标签
const handleCreateTag = async (name) => {
  try {
    tagLoading.value = true
    const res = await tagApi.createTag(name)

    // 将新创建的标签添加到选项中
    const newTag = {
      name: name,
      color: res.color || primaryColor,
      count: 0,
    }
    tagOptions.value.unshift(newTag)

    // 选中新创建的标签
    if (!props.articleForm.tags) {
      props.articleForm.tags = []
    }

    // 确保不重复添加
    if (!props.articleForm.tags.includes(name)) {
      props.articleForm.tags.push(name)
    }

    ElMessage.success('标签创建成功')
  } catch (error) {
    console.error('创建标签失败:', error)
    ElMessage.error('创建标签失败')
  } finally {
    tagLoading.value = false
  }
}

// 上传封面图片前的处理
const beforeCoverUpload = (file) => {
  const isImage = /^image\/(jpeg|png|gif)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 封面上传成功的处理
const handleCoverSuccess = (res) => {
  if (res.code === 1) {
    // 直接修改父组件传递的 articleForm，使用 picUrl
    props.articleForm.picUrl = res.data
    // 设置默认封面风格为小图模式
    props.articleForm.coverStyle = '1'
    // 触发更新事件
    emit('update:articleForm', { ...props.articleForm })
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 处理自动生成摘要
const handleAutoGenerate = async () => {
  if (!props.articleForm.content) {
    ElMessage.warning('请先输入文章内容')
    return
  }

  try {
    isGenerating.value = true

    // 构造请求数据
    const requestData = {
      content: props.articleForm.content,
    }

    // 如果有文章ID，则传递ID
    const articleId = props.articleForm.id
    if (articleId) {
      requestData.id = articleId
    }

    // 调用后端接口生成摘要
    const res = await articleApi.autoSummary(requestData)

    if (res) {
      // 更新摘要内容
      props.articleForm.description = res
      // 触发父组件更新
      emit('update:articleForm', { ...props.articleForm })
      ElMessage.success('摘要生成成功')
    } else {
      ElMessage.error('摘要生成失败，请重试')
    }
  } catch (error) {
    console.error('生成摘要失败:', error)
    ElMessage.error('生成摘要失败，请重试')
  } finally {
    isGenerating.value = false
  }
}

// 删除封面图
const handleDeleteCover = () => {
  props.articleForm.picUrl = ''
  props.articleForm.coverStyle = '0'
  emit('update:articleForm', { ...props.articleForm })
}
</script>

<style lang="scss" scoped>
@use 'sass:color';

// 配置面板容器
.config-panel {
  position: absolute;
  top: 0;
  bottom: 0;
  right: -380px;
  width: 380px;
  background-color: $bg-base;
  border-left: 1px solid $border-base;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  z-index: 10;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);

  // 显示状态
  &.is-visible {
    right: 0;
  }

  // 面板头部样式
  .panel-header {
    padding: 20px;
    border-bottom: 1px solid $border-light;
    @include flex-between;

    .panel-title {
      font-size: $font-size-medium;
      font-weight: 500;
      color: $text-primary;
    }

    .close-btn {
      font-size: 18px;
      color: $text-secondary;

      &:hover {
        color: $text-primary;
      }
    }
  }

  // 面板主体样式
  .panel-body {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    @include scrollbar;

    :deep(.el-form) {
      // 表单项基础样式
      .el-form-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          padding-bottom: 8px;
          line-height: 1.5;
          font-weight: 500;
        }
      }
    }

    // 文章类型按钮组
    .type-group {
      width: 100%;
      display: flex;

      :deep(.el-radio-button__inner) {
        flex: 1;
        text-align: center;
      }
    }

    // 封面风格按钮组
    .cover-style-group {
      width: 100%;
      display: flex;

      :deep(.el-radio-button__inner) {
        flex: 1;
        text-align: center;
      }
    }

    // 排序值输入框
    .order-input {
      width: 100%;

      :deep(.el-input-number) {
        width: 100%;
      }
    }

    // 辅助类
    .mt-2 {
      margin-top: 8px;
    }

    // 封面上传组件样式
    .cover-uploader {
      width: 100%;
      border: 1px dashed $border-base;
      border-radius: $border-radius-base;
      overflow: hidden;
      transition: $transition-base;
      position: relative;

      &:hover {
        border-color: $primary-color;
      }

      .uploader {
        width: 100%;

        :deep(.el-upload) {
          width: 100%;
          cursor: pointer;
        }
      }

      .cover-image {
        width: 100%;
        height: 160px;
        display: block;
      }

      .upload-placeholder {
        width: 100%;
        height: 160px;
        @include flex-center;
        flex-direction: column;
        gap: 8px;
        color: $text-secondary;
        transition: $transition-base;
        background-color: $bg-light;

        .el-icon {
          font-size: 32px;
        }

        span {
          font-size: 14px;
        }
      }

      .image-error {
        width: 100%;
        height: 160px;
        background-color: $bg-light;
        @include flex-center;
        color: $text-secondary;

        .el-icon {
          font-size: 32px;
        }
      }

      .delete-cover {
        position: absolute;
        right: 8px;
        top: 8px;
        background: rgba(0, 0, 0, 0.5);
        color: #fff;
        border: none;
        padding: 4px;
        border-radius: 4px;
        transition: $transition-base;

        &:hover {
          background: rgba(0, 0, 0, 0.7);
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    // 标签选择器样式
    :deep(.el-select) {
      .el-select__tags {
        .el-tag {
          border-radius: 12px;
          padding: 0 12px;
          height: 24px;
          line-height: 24px;

          .el-tag__close {
            right: -4px;
          }
        }
      }
    }

    // 标签选项样式
    .tag-option {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-tag {
        border: none;
        padding: 4px 12px;
        border-radius: 12px;
        font-weight: 500;
      }

      .tag-count {
        font-size: 12px;
        color: $text-secondary;
      }
    }

    // 表单标签包装器
    .form-label-wrap {
      display: flex;
      align-items: center;
      gap: 4px;

      // 必填标识样式
      .required {
        &::before {
          content: '*';
          color: $danger-color;
          margin-right: 4px;
        }
      }

      .info-icon {
        font-size: 14px;
        color: $text-secondary;
        cursor: help;
        transition: $transition-base;

        &:hover {
          color: $primary-color;
        }
      }
    }

    // 摘要输入区域
    .summary-wrapper {
      position: relative;
      width: 100%;

      :deep(.el-textarea) {
        width: 100%;

        .el-textarea__inner {
          padding-right: 48px;
          transition: all 0.3s ease;

          &:focus {
            box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
          }
        }

        .el-input__count {
          bottom: 6px;
          right: 8px;
          color: $text-secondary;
          font-size: 12px;
        }
      }

      // 自动生成按钮
      .auto-generate {
        position: absolute;
        right: 8px;
        top: 8px;

        .generate-btn {
          width: auto;
          min-width: 32px;
          height: 32px;
          padding: 0 8px;
          border: none;
          border-radius: 6px;
          background: transparent;
          color: $text-secondary;
          transition: all 0.3s ease;
          display: flex;
          align-items: center;
          gap: 4px;

          &:hover:not(:disabled) {
            color: $primary-color;
            background: rgba($primary-color, 0.1);
            transform: scale(1.05);
          }

          &:active:not(:disabled) {
            transform: scale(0.95);
          }

          &:disabled {
            opacity: 0.7;
            cursor: not-allowed;
          }

          .el-icon {
            font-size: 18px;
          }

          .generating-text {
            font-size: 12px;
            font-weight: 500;
          }
        }

        // 生成中状态
        &.is-generating {
          .generate-btn {
            color: $primary-color;
            background: rgba($primary-color, 0.1);
            animation: pulse 1.5s infinite;

            .generating-text {
              animation: blink 1.5s infinite;
            }
          }
        }
      }
    }
  }
}

// 工具类
.w-full {
  width: 100%;
}

// 添加脉冲动画
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

// 添加闪烁动画
@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0.3;
  }
}
</style>
